package com.tqw.item.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tqw.entity.Result;
import com.tqw.es.feign.EsFeign;
import com.tqw.item.mapper.ItemCatMapper;
import com.tqw.item.mapper.ItemDescMapper;
import com.tqw.item.mapper.ItemMapper;
import com.tqw.pojo.Area;
import com.tqw.pojo.Item;
import com.tqw.pojo.ItemCat;
import com.tqw.pojo.ItemDesc;
import com.tqw.item.service.FileService;
import com.tqw.item.service.ItemService;
import com.tqw.shipping.feign.AreaFeignClient;
import com.tqw.shipping.feign.ShippingFeignClient;
import com.tqw.vo.AreaCas;
import com.tqw.vo.ItemVO;
import com.tqw.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PutMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Alex
 */
@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private ItemDescMapper itemDescMapper;

    @Autowired
    private FileService fileService;

    @Autowired
    private ItemCatMapper itemCatMapper;

    @Autowired
    private EsFeign esFeign;


    /**
     * 拉取当前用户的商品并分页展示
     * @param pageResult
     * @return
     */
    @Override
    public PageResult getItemList(PageResult pageResult,Integer userId) {
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        //动态sql
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        boolean flag2 =  (pageResult.getItemStatus()!=null);
        queryWrapper.like(flag, "title",pageResult.getQuery())
                    .eq(flag2,"status", pageResult.getItemStatus())
                    .eq("user_id", userId);
        //使用MP的page对象
        Page<Item> page = new Page<>(pageResult.getPageNum(), pageResult.getPageSize());
        Page<Item> itemPage = itemMapper.selectPage(page, queryWrapper);

        long total = itemPage.getTotal();
        List<Item> records = itemPage.getRecords();
        return pageResult.setTotal(total).setRows(records);
    }

    /**
     * 修改商品状态
     * @param item
     */
    @Override
    @Transactional
    public void updateItemStatus(Item item) {

        itemMapper.updateById(item);
    }

    /**
     * 删除商品及其图片
     * @param id
     */
    @Override
    @Transactional
    public void deleteItemById(Integer id) {

        //删除详情中的所有图片
        ItemDesc itemDesc = itemDescMapper.selectById(id);
        String[] descImages =itemDesc.getImages().split(",");
        for (String path:descImages){
            fileService.deleteFile(path);
        }

        //todo 调用es模块
//        esFeign.deleteItem(id);

        //删除商品数据
        itemMapper.deleteById(id);
        itemDescMapper.deleteById(id);
    }

    /**
     * 根据id查找商品
     * @param id
     * @return
     */
    @Override
    public Item findItemById(Integer id) {

        return itemMapper.selectById(id);
    }


    /**
     * 修改商品信息
     * @param item
     */
    @Override
    @Transactional
    public void updateItemById(Item item) {

        itemMapper.updateById(item);

        //todo 调用es模块
//        esFeign.update(item);
    }

    /**
     * 新增商品
     * @param itemVO
     */
    @Override
    @Transactional
    public void saveItem(ItemVO itemVO,Integer userId) {
        //入库商品表
        Item item = itemVO.getItem();

        ItemDesc itemDesc = itemVO.getItemDesc();

        // '1' 代表处于在售状态
        item.setStatus('1');
        //设置商品所属用户的id
        item.setUserId(userId);
        //获取并设置商品所在分类的一级id
        //获取cat_id
        Integer catId = item.getCatId();
        //查出所属的商品分类
        ItemCat itemCat = itemCatMapper.selectById(catId);
        //获取二级菜单
        Integer parentId = itemCat.getParentId();
        ItemCat itemCat_parent = itemCatMapper.selectById(parentId);
        //获取一级菜单id
        Integer grandpa_id = itemCatMapper.selectById(itemCat_parent.getParentId()).getId();
        item.setGrandfatherCatId(grandpa_id);
        //通过itemDesc中的图片信息获取第一张图片,作为item的首页图片
        String images = itemDesc.getImages();
        String fontImage;
        //判断images中是否有多张图片
        if (images!=null&&images.contains(",")){
            fontImage = images.substring(0,images.indexOf(','));
        }else{
            fontImage = images;
        }
        item.setFontImage(fontImage);
        itemMapper.insert(item);

        //todo 调用es模块
//        esFeign.save(item);

        //商品入库后回显出id
        itemDesc.setId(item.getId());
        itemDescMapper.insert(itemDesc);
    }

    /**
     * 查询所有状态为'1'的商品信息(供首页展示商品使用)
     * @return
     */
    @Override
    public List<Item> findItemList() {
        //select id,title,price,font_image,grandfather_cat_id from item where status=1
        QueryWrapper<Item> itemQueryWrapper = new QueryWrapper<>();
        itemQueryWrapper.eq("status", '1');
        List<Item> itemList = itemMapper.selectList(itemQueryWrapper);
        return itemList;
    }

    /**
     * 商品下架(状态为1的商品的状态改为0)
     * @param id
     */
    @Override
    @Transactional
    public void downItem(Integer id) {
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id)
                    .eq("status", '1');
        Item item = itemMapper.selectOne(queryWrapper);
        if (item!=null){
            item.setStatus('0');
            itemMapper.updateById(item);
        }
    }

    /**
     * 商品上架(状态为0的商品的状态改为1)
     * @param id
     */
    @Override
    @Transactional
    public void putawayItem(Integer id) {
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id)
                .eq("status", '0');
        Item item = itemMapper.selectOne(queryWrapper);
        if (item!=null){
            item.setStatus('1');
            itemMapper.updateById(item);
        }
    }


}
